package com.example.AIstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.AIstudy.dao.CuoTiJiDao;
import com.example.AIstudy.domain.CuoTiJi;
import com.example.AIstudy.domain.FalseReason;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.CompositionService;
import com.example.AIstudy.service.CuoTiJiService;
import com.example.AIstudy.service.FalseReasonService;
import com.example.AIstudy.service.TranslationService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CuoTiJiServiceImpl extends ServiceImpl<CuoTiJiDao, CuoTiJi> implements CuoTiJiService {

    @Autowired
    CuoTiJiDao cuoTiJiDao;

    @Autowired
    FalseReasonService falseReasonService;

    @Autowired
    CompositionService compositionService;
    @Autowired
    TranslationService translationService;

    public IPage<CuoTiJi> findCuoTiJi(Map<String, Object> condition, Integer pageNum, Integer pageSize){
        IPage page = new Page(pageNum, pageSize);
        QueryWrapper<CuoTiJi> qw = new QueryWrapper<>();
        //查询用户的错题信息
        qw.eq("stuID", condition.get("userID"));
        //查询错题信息的时候可以筛选
        if(condition.containsKey("order")){
            //升序
            if(condition.get("order").equals("ASC")){
                qw.orderByAsc("insertTime");
            }
            //倒序
            else{
                qw.orderByDesc("insertTime");
            }
        }
        //根据错题的题型标签查看错题信息
        if(condition.get("category")!=null){
            List<String> category= (List<String>) condition.get("category");
            qw.in("category", category);
        }
        //要保证查询出来的是第一道错题
        qw.and(wq -> {
            // 拼接sql
            wq.isNotNull("sonProID")
                    .or()
                    .ne("category","yuedu");
        });
        //根据错题的错误标签查看错题信息
        if(condition.get("falseReason")!=null){
            List<Integer> falseReason= (List<Integer>) condition.get("falseReason");
            qw.in("falseReasonID", falseReason);
        }
        if(condition.get("field")!=null){
            List<String> field= (List<String>) condition.get("field");
            Boolean flag=false;
            for(int i=0;i<field.size();i++){
                if(field.get(i).equals("其它")){
                    flag=true;
                    qw.and(wq -> {
                        // 拼接sql
                        wq.isNull("field")
                                .or()
                                .in("field", field);
                    });
                }
            }
            if(!flag)qw.in("field", field);
        }if(condition.get("startTime")!=null){
            qw.ge("insertTime", condition.get("startTime"));
        }
        if(condition.get("endTime")!=null){
            qw.le("insertTime", condition.get("endTime"));
        }
        IPage page1 =cuoTiJiDao.findCuoTiJi(page, qw);
        List<CuoTiJi>records=page1.getRecords();
        int size=records.size();
        //对阅读题进行封装，对原因进行设置
        for(int i=0;i<size;i++){
            CuoTiJi cuoTiJi=records.get(i);
            if(cuoTiJi.getFalseReasonID()!=null)
                cuoTiJi.setFalseReason(falseReasonService.getById(cuoTiJi.getFalseReasonID()).getFalseReason());
            if(cuoTiJi.getCategory().equals("yuedu")){
                //对阅读题进行封装
                records.set(i,fengzhuangYuedu(cuoTiJi));
            }else if(cuoTiJi.getCategory().equals("zuowen")){
                cuoTiJi.setCompositionDetail(compositionService.getById(cuoTiJi.getCompCommentID()));
            }else if(cuoTiJi.getCategory().equals("fanyi")){
                cuoTiJi.setTranslateDetail(translationService.getById(cuoTiJi.getTransCommentID()));
            }
        }
        //封装每道题的标签
//        for(int i=0;i<size;i++){
//            CuoTiJi cuoTiJi=records.get(i);
//            Map<String,String>map=new HashMap<>();
//            // 封装类别标签
//            map.put("category", cuoTiJi.getCategory());
//            // 封装错因标签
//            int falseReasonID= Integer.parseInt(cuoTiJi.getFalseReasonIDs());
//            String falseReason= String.valueOf(falseReasonService.getById(falseReasonID));
//            map.put("falseReason", falseReason);
//            // 封装领域标签
//            map.put("field", cuoTiJi.getField());
//            // 更新错题的标签信息
//            cuoTiJi.setTags(map);
//        }
//        page1.setRecords(records);
        return page1;
    }

    //获取错题数量

    public int getCuoTiNumByUserID(Integer userID){
        return cuoTiJiDao.getCuoTiNumByUserID(userID);
    }


    //获取错题的详细信息,如果是阅读题，需要进行额外的封装
    @Transactional(rollbackFor = AIstudyException.class)
    public CuoTiJi getCuoTiDetailByID(Integer cuotiID) throws AIstudyException {
        try {
            CuoTiJi cuoTiJi = cuoTiJiDao.selectById(cuotiID);
            //设置错题的原因
            if(cuoTiJi.getFalseReasonID()!=null){
                cuoTiJi.setFalseReason(falseReasonService.getById(cuoTiJi.getFalseReasonID()).getFalseReason());
            }
            List<Integer> sonList = null;
            //阅读题
            if (cuoTiJi.getSonProID() != null) {
                return fengzhuangYuedu(cuoTiJi);
            }else if(cuoTiJi.getCategory().equals("zuowen")){
                cuoTiJi.setCompositionDetail(compositionService.getById(cuoTiJi.getCompCommentID()));
            }else if(cuoTiJi.getCategory().equals("fanyi")){
                cuoTiJi.setTranslateDetail(translationService.getById(cuoTiJi.getTransCommentID()));
            }
            return cuoTiJi;
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.QUERY_ERROR,"查询错题的详细信息失败");
        }
    }

    // 更新错题的批注信息
    public void updateUserComment(Integer cuotiID,String userComment) throws AIstudyException {
        try{
            cuoTiJiDao.updateUserComment(cuotiID, userComment);
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"删除错题信息失败");
        }
    }

    @Override
    public void deleteCuoti(Integer cuotiID) throws AIstudyException{

        try{
            cuoTiJiDao.deleteById(cuotiID);
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.DELETE_ERROR,"删除错题信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = AIstudyException.class)
    public Map<String, List<Object>> getTagsByTime(Integer userID, Timestamp startTime, Timestamp endTime) throws AIstudyException{
        try{
            QueryWrapper<CuoTiJi> qw1 = new QueryWrapper<>();
            Map<String, List<Object>>map=new HashMap<>();
            //根据时间获取到类别信息、领域信息和错误原因，封装成map返回给前端
            qw1.eq("stuID", userID);
            if(startTime!=null){
                qw1.ge("insertTime", startTime);
            }
            if(endTime!=null){
                qw1.le("insertTime", endTime);
            }
            qw1.and(wq -> {
                // 拼接sql
                wq.isNotNull("sonProID")
                        .or()
                        .ne("category","yuedu");
            });
            List<FalseReason>falseReasonList=cuoTiJiDao.getFalseReasonByTime(qw1);
            map.put("field", cuoTiJiDao.getFieldsByTime(qw1));
            List<Object>fields= cuoTiJiDao.getFieldsByTime(qw1);
            String str="其它";
            for(int i=0;i<fields.size();i++){
                if(fields.get(i)==null){
                    fields.set(i,str);
                }
            }
            map.put("category", cuoTiJiDao.getCategoriesByTime(qw1));
            List<Object> objectList = new ArrayList<>();
            for (FalseReason reason : falseReasonList) {
                objectList.add(reason);
            }
            map.put("falseReason", objectList);
            return map;
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new AIstudyException(AIstudyException.ErrorType.QUERY_ERROR,"查找标签信息失败");
        }
    }
    public void updateRedoCuoti(List<Integer> list){
        //根据ID来更新需要重做的记录
        QueryWrapper<CuoTiJi> qw = new QueryWrapper<>();
        qw.in("id", list);
        cuoTiJiDao.updateRedoCuoti(qw);
    }

    public List<CuoTiJi> queryCuotiForRedo(Integer userID, List<String>category,List<String>field,List<Integer>falseReason){
        QueryWrapper<CuoTiJi> qw = new QueryWrapper<>();
        qw.eq("needRedo", 1);
        qw.eq("stuID", userID);
        if(category!=null){
            qw.in("category", category);
        }
        if(field!=null){
            qw.in("field", field);
        }
        if(falseReason!=null){
//            int size=falseReason.size();
//            List<Integer>falseReasonIDs=new ArrayList<>();
//            for(int i=0;i<size;i++){
//                falseReasonIDs.add(falseReason.get(i).getId());
//            }
            qw.in("falseReasonID", falseReason);
        }
        qw.and(wq -> {
            // 拼接sql
            wq.isNotNull("sonProID")
                    .or()
                    .ne("category","yuedu");
        });
        List<CuoTiJi>cuoTiJis=cuoTiJiDao.queryCuotiForRedo(qw);
        int size=cuoTiJis.size();
        //对阅读题进行封装，对原因进行设置
        for(int i=0;i<size;i++){
            CuoTiJi cuoTiJi=cuoTiJis.get(i);
            if(cuoTiJi.getFalseReasonID()!=null){
                cuoTiJi.setFalseReason(falseReasonService.getById(cuoTiJi.getFalseReasonID()).getFalseReason());
            }
            if(cuoTiJi.getCategory().equals("yuedu")){
                //对阅读题进行封装
                cuoTiJis.set(i,fengzhuangYuedu(cuoTiJi));
            }
        }
        return cuoTiJis;
    }

    //对阅读题进行封装
    public CuoTiJi fengzhuangYuedu(CuoTiJi cuoTiJi){
        //获取子阅读题的ID
        String[] sonlistStr = cuoTiJi.getSonProID().split(",");
        List<Integer> sonList = new ArrayList<>();
        int sizeSon = sonlistStr.length;
        for (int j = 0; j < sizeSon; j++) {
            sonList.add(Integer.valueOf(sonlistStr[j]));
        }
        //获取子阅读题
        List<CuoTiJi>cuoTiJis=cuoTiJiDao.selectBatchIds(sonList);
        cuoTiJi.setCuoTiList(cuoTiJis);
        int size=cuoTiJis.size();
        for(int i=0;i<size;i++){
            CuoTiJi tmp2=cuoTiJis.get(i);
            if(tmp2.getFalseReasonID()!=null){
                tmp2.setFalseReason(falseReasonService.getById(tmp2.getFalseReasonID()).getFalseReason());
            }
        }
        CuoTiJi tmp=new CuoTiJi();
        //设置用户id
        tmp.setId(cuoTiJi.getId());
        //设置答案
        tmp.setAnswer(cuoTiJi.getAnswer());
        //设置选项
        tmp.setChoice1(cuoTiJi.getChoice1());
        tmp.setChoice2(cuoTiJi.getChoice2());
        tmp.setChoice3(cuoTiJi.getChoice3());
        tmp.setChoice4(cuoTiJi.getChoice4());
        //设置用户答案
        tmp.setStuAnswer(cuoTiJi.getStuAnswer());
        //设置选项个数
        tmp.setChoiceNum(cuoTiJi.getChoiceNum());
        //这是问题
        tmp.setProblem(cuoTiJi.getProblem());
        //设置其它信息
        tmp.setAiComment(cuoTiJi.getAiComment());
        tmp.setUserComment(cuoTiJi.getUserComment());
        tmp.setFalseReasonID(cuoTiJi.getFalseReasonID());
        tmp.setFalseReason(cuoTiJi.falseReason);
        //将题目放到到第一道
        cuoTiJi.getCuoTiList().add(0, tmp);
        return cuoTiJi;
    }

    public void UpdateUserComment(Integer cuotiID,String userComment) throws AIstudyException{
        try {
            cuoTiJiDao.UpdateUserComment(cuotiID, userComment);
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"更新标注信息失败");
        }
    }

    @Transactional(rollbackFor = AIstudyException.class)
    //完成习题的插入
    public void insertCuoti(CuoTiJi cuoTiJi) throws AIstudyException{
        try{
            Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
            List<FalseReason>falseReasonList=falseReasonService.findReasonByUserID(cuoTiJi.getStuID());
            List<String>falseReason2=new ArrayList<>();
            for(int j=0;j<falseReasonList.size();j++){
                falseReason2.add(falseReasonList.get(j).getFalseReason());
            }
            String category=cuoTiJi.getCategory();
            cuoTiJi.setInsertTime(currentTimestamp);
            //插入选择题，需要判断选择题的正误
            if(category.equals("xuanze")){
                fengzhuangFalseReason(cuoTiJi,falseReason2,falseReasonList);
                if(cuoTiJi.getScore()==0){
                    cuoTiJi.setScore(3);
                }
                if(cuoTiJi.getAnswer().equals(cuoTiJi.getStuAnswer())){
                    cuoTiJi.setRight(true);
                    cuoTiJi.setStuScore(3);
                }
                cuoTiJiDao.insert(cuoTiJi);
            }
            //插入阅读和翻译题
            else if(!category.equals("yuedu")){
                fengzhuangFalseReason(cuoTiJi,falseReason2,falseReasonList);

                if(cuoTiJi.getScore()==0&&category.equals("zuowen")){
                    cuoTiJi.setScore(25);
                }
                else if(cuoTiJi.getScore()==0&&category.equals("fanyi")){
                    cuoTiJi.setScore(15);
                }
                cuoTiJiDao.insert(cuoTiJi);
            }else{
                //插入阅读题
                List<CuoTiJi>cuoTiJis=cuoTiJi.getCuoTiList();
                Integer UserID=cuoTiJi.getStuID();
                int size=cuoTiJis.size();
                StringBuilder sonProID=new StringBuilder();
                if(cuoTiJi.getScore()==0)cuoTiJi.setScore(3);
                for(int i=1;i<size;i++) {
                    CuoTiJi cuoTiJi1 = cuoTiJis.get(i);
                    fengzhuangFalseReason(cuoTiJi1,falseReason2,falseReasonList);
                    cuoTiJi1.setInsertTime(currentTimestamp);
                    cuoTiJi1.setStuID(UserID);
                    if(cuoTiJi1.getAnswer().equals(cuoTiJi1.getStuAnswer())){
                        cuoTiJi1.setRight(true);
                        cuoTiJi1.setStuScore(cuoTiJi.getScore());
                    }
                    if(cuoTiJi1.getScore()==0)cuoTiJi1.setScore(cuoTiJi.getScore());
                    cuoTiJiDao.insertCuotiji(cuoTiJi1);
                    sonProID.append(cuoTiJi1.getId());
                    sonProID.append(",");
                }
                //封装第一个错题
                CuoTiJi tmp=cuoTiJis.get(0);
                cuoTiJi.setInsertTime(currentTimestamp);
                cuoTiJi.setProblem(tmp.getProblem());
                cuoTiJi.setAnswer(tmp.getAnswer());
                cuoTiJi.setChoiceNum(tmp.getChoiceNum());
                cuoTiJi.setChoice1(tmp.getChoice1());
                cuoTiJi.setChoice2(tmp.getChoice2());
                cuoTiJi.setChoice3(tmp.getChoice4());
                cuoTiJi.setChoice4(tmp.getChoice4());
                cuoTiJi.setAiComment(tmp.getAiComment());
                cuoTiJi.setStuAnswer(tmp.getStuAnswer());
                cuoTiJi.setFalseReason(tmp.getFalseReason());
                if(cuoTiJi.getAnswer().equals(cuoTiJi.getStuAnswer())){
                    cuoTiJi.setRight(true);
                    cuoTiJi.setStuScore(cuoTiJi.getScore());
                }
                cuoTiJi.setSonProID(sonProID.toString().substring(0, sonProID.length()-1));
                fengzhuangFalseReason(cuoTiJi,falseReason2,falseReasonList);
                cuoTiJiDao.insert(cuoTiJi);
                //将id封装到第一道题目中
                tmp.setId(cuoTiJi.getId());
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"增加错题失败");
        }

    }
    //根据用户的falseReason标签，判断是否在reason表中存在，如果存在则获取id，如果不存在
    public void fengzhuangFalseReason(CuoTiJi cuoTiJi,List<String>falseReason2,List<FalseReason>falseReasonList){
        //不处理空的错因标签
        if(cuoTiJi.getFalseReason()==null){
            cuoTiJi.setFalseReasonID(0);
            return;
        }
        //如果标签本来不存在，则增加标签
        if (!falseReason2.contains(cuoTiJi.getFalseReason())) {
            FalseReason falseReason = new FalseReason();
            falseReason.setFalseReason(cuoTiJi.getFalseReason());
            falseReason.setUserID(cuoTiJi.getStuID());
            falseReasonService.insertReason(falseReason);
            //更新错题集的信息
            cuoTiJi.setFalseReasonID(falseReason.getId());
            falseReasonList.add(falseReason);
            falseReason2.add(falseReason.getFalseReason());
        } else {
            //直接获取到错因的ID进行添加
            int index = falseReason2.indexOf(cuoTiJi.getFalseReason());
            cuoTiJi.setFalseReasonID(falseReasonList.get(index).getId());
        }
    }

    @Transactional(rollbackFor = AIstudyException.class)
    public void updateCuoti(CuoTiJi cuoTiJi)throws AIstudyException{
        try{
            List<FalseReason>falseReasonList=falseReasonService.findReasonByUserID(cuoTiJi.getStuID());
            List<String>falseReason2=new ArrayList<>();
            for(int j=0;j<falseReasonList.size();j++){
                falseReason2.add(falseReasonList.get(j).getFalseReason());
            }
            String category=cuoTiJi.getCategory();
            if(!category.equals("yuedu")){
                if(cuoTiJi.getFalseReason()!=null)fengzhuangFalseReason(cuoTiJi, falseReason2, falseReasonList);
                updateById(cuoTiJi);
            }else{
                List<CuoTiJi>cuoTiJis=cuoTiJi.getCuoTiList();
                int size=cuoTiJis.size();
                Integer stuID=cuoTiJi.getStuID();
                //对第一个对象进行额外的封装
                CuoTiJi cuoTiJi1=cuoTiJis.get(0);
                cuoTiJi1.setContent(cuoTiJi.getContent());
                cuoTiJi1.setCategory(cuoTiJi.getCategory());
                cuoTiJi1.setField(cuoTiJi.getField());
                cuoTiJi1.setEsID(cuoTiJi.getEsID());
                cuoTiJi1.setSonProID(cuoTiJi.getSonProID());
                //循环添加
                for(int i=0;i<size;i++){
                    CuoTiJi tmp=cuoTiJis.get(i);
                    if(tmp.getFalseReason()!=null)fengzhuangFalseReason(tmp, falseReason2, falseReasonList);
                    tmp.setStuID(stuID);
                    cuoTiJiDao.updateById(tmp);
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"更新错题信息失败");
        }
    }
    public void updateCuotiRedoNum(Integer redoNum,Integer cuotiID){
        cuoTiJiDao.updateCuotiRedoNum(redoNum, cuotiID);
    }
}
